from PyQt6.QtCore import *
from PyQt6.QtNetwork import *
from PyQt6.QtGui import *
import json
import cx_Oracle

class ClientHandlerThread(QThread):

    userName = ""

    # socket_descriptor is an int variable
    def __init__(self, socket, parent=None):
        super().__init__(parent)
        self.socket = socket
        self.cursor = self.connectToOracle()

    def connectToOracle(self):
        try:
            connection = cx_Oracle.connect('C##WLK/060050aaa@localhost:1522/XE')
            return connection.cursor()

        except cx_Oracle.DatabaseError as e:
            error, = e.args
            print("Oracle-Error-Code:", error.code)
            print("Oracle-Error-Message:", error.message)

    def run(self):
        self.socket.readyRead.connect(self.handle_ready_read)
        print('signal connect')
        while True:
            if self.socket.state() == QAbstractSocket.SocketState.ConnectedState:
                # 进入Qt事件循环，等待事件触发
                loop = QEventLoop()
                loop.exec()
            else:
                break

    def handle_ready_read(self):
        client_socket = self.sender()
        data = client_socket.readAll().data().decode()
        json_data = json.loads(data)
        print(json_data)
        if json_data[0]["message"] == 'login':
            print('message is login')
            username = json_data[1]["username"]
            password = json_data[1]["password"]
            self.login(username, password)
            if json_data[1]["type"] == "company":
                print('select')
                self.cursor.execute("SELECT * FROM baoxiao")
                result = self.cursor.fetchone()
                print(result)
                if result is not None:
                    print('json')
                    info = [{"message": "data"}]
                    blob = result[2].read()
                    clob = result[1].read()
                    print(blob, clob)
                    print(type(blob), type(clob))
                    info.append({"name": result[0], "info": clob, "image": blob.decode('utf-8')})
                    json_result = "###" + json.dumps(info)
                    print(json_result)
                    self.socket.write(json_result.encode())
        if json_data[0]["message"] == 'images':
            print('message is images')
            image_json_data = json.loads(json_data[2])
            print(image_json_data['image'])
            print('read byte')
            image_data = QByteArray.fromBase64(image_json_data["image"].encode())
            print('read image')
            image = QImage.fromData(image_data)
            print('change image')
            image.save("result.jpg")
            print('save')

            try:
                self.cursor.execute("INSERT INTO baoxiao Values(:name, :info, :image)", name=json_data[1]["username"], info=json.dumps(json_data[2]), image=image_json_data["image"].encode())
                self.cursor.execute("commit")

            except cx_Oracle.IntegrityError:
                print("it has been existed")
            print('insert')

    def login(self, username, password):
        print('query')
        print(username, password)
        query = "SELECT password FROM myUsers WHERE username = :username"
        self.cursor.execute(query, username=username)
        print('finish query')
        result = self.cursor.fetchone()
        print('get result')
        print(result)
        if password == result[0]:
            data = [{"message": "login"}, {"result": "success"}]
            json_data = "###" + json.dumps(data)
            self.socket.write(json_data.encode())
